package com.jing.ListAdapter;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.jing.ListAdapter.adapter.MyListAdapter;
import com.jing.ListAdapter.entity.Student;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private ListView listView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

//        List<String> fruits = new ArrayList<>();
//
//        fruits.add("苹果");
//        fruits.add("香蕉");
//        fruits.add("普通");
//        fruits.add("西瓜");
        students=new ArrayList<>();
        students.add(new Student("张三",21,"男"));
        students.add(new Student("李四",21,"女"));
        students.add(new Student("王五",21,"男"));

         listView =findViewById(R.id.listview);
         listView.setAdapter(new MyListAdapter(this,students));
         listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
             @Override
             public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                 String selectedItem = students.get(position).getName();
                 Toast.makeText(MainActivity.this, selectedItem, Toast.LENGTH_SHORT).show();
             }
         });
        listView.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {
            @Override
            public void onCreateContextMenu(ContextMenu arg0, View view, ContextMenu.ContextMenuInfo arg1) {
                arg0.setHeaderTitle("选择操作");
                arg0.add(0, 4, 0, "移出");
            }
        });
    }
    List<Student> students;
    public boolean onContextItemSelected(@NonNull MenuItem item) {
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        //获取点击的item的id
        if (item.getItemId() == 4) {
            Student student = students.get((int)info.id);
            Toast.makeText(this, "移出了姓名为"+student.getName()+"的学生", Toast.LENGTH_SHORT).show();
            students.remove(student);
            listView.setAdapter(new MyListAdapter(this,students));
            return true;
        }

        return super.onContextItemSelected(item);
    }
}